package com.suning.park.admin.util.epps;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 参数处理
 * Created by Administrator on 2017/1/12.
 */
public class Digest {
    private static final String EQ_SYMBOL = "=";
    private static final String AND_SYMBOL = "&";

    public static String digest(String str)
            throws UnsupportedEncodingException {
        String md5 = null;
        md5 = MD5.digest(str, "UTF-8");
        return md5;
    }

    public static String digest(Map<String, String> map, List<String> excudeKeylist)
            throws UnsupportedEncodingException {
        TreeMap treeMap = treeMap(map, excudeKeylist);
        return digest(mapToString(treeMap));
    }

    public static TreeMap<String, String> treeMap(Map<String, String> map, List<String> excudeKeylist) {
        Comparator stringComparator = new StringComparator();
        TreeMap treeMap = new TreeMap(stringComparator);
        treeMap.putAll(map);

        if ((null != excudeKeylist) && (excudeKeylist.size() > 0))
            for (Iterator i$ = excudeKeylist.iterator(); i$.hasNext(); ) {
                String key = (String) i$.next();
                treeMap.remove(key);
            }

        return treeMap;
    }

    public static String mapToString(Map<String, String> map) {
        StringBuilder result = new StringBuilder();
        for (Iterator i$ = map.entrySet().iterator(); i$.hasNext(); ) {
            Map.Entry entry = (Map.Entry) i$.next();
            String value = (entry.getValue() == null) ? "" : ((String) entry.getValue()).trim();
            result.append((String) entry.getKey()).append("=").append(value).append("&");
        }
        if (result.length() > 0)
            result.deleteCharAt(result.length() - 1);

        return result.toString().trim();
    }

    static class StringComparator implements Comparator<String> {

        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    }
}
